<template>
  <el-dialog
    title="申请提现"
    :modelValue="visible"
    @update:modelValue="$emit('update:visible', $event)"
    :fullscreen="mobile"
    class="dialog-content-clear"
    width="520px"
    destroy-on-close
  >
    <div class="p20" v-loading="loading">
      <!-- 账户未配置提示 -->
      <div v-if="!hasAccount">
        <el-alert
          title="您尚未配置收款账户，请先完成账户配置"
          type="warning"
          :closable="false"
          show-icon
        />
        <div class="text-center mt20">
          <el-button type="primary" @click="goToAccountSetting">立即设置</el-button>
        </div>
      </div>
      
      <!-- 账户已配置 -->
      <div v-else>
        <el-alert
          title="提示：提现申请提交后，平台将在1-3个工作日内处理您的申请并转账到您的账户。"
          type="warning"
          :closable="false"
        />

        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" class="mt20">
          <el-form-item label="提现金额" prop="amount">
            <el-input v-model="form.amount" disabled>
              <template #append>元</template>
            </el-input>
          </el-form-item>

          <!-- 显示已配置的账户信息 -->
          <el-form-item label="收款账户">
            <div class="account-info">
              <p><span class="label">账户类型：</span>{{ accountInfo.accountType === '1' ? '个人账户' : '企业账户' }}</p>
              <p><span class="label">开户银行：</span>{{ accountInfo.bankName }}</p>
              <p><span class="label">银行账号：</span>{{ accountInfo.bankAccount }}</p>
              <p><span class="label">账户名：</span>{{ accountInfo.accountType === '1' ? accountInfo.accountHolder : accountInfo.companyName }}</p>
              <p><span class="label">状态</span>{{ accountInfo.auditStatus === '1' ? '正常' : '审核中' }}</p>
            </div>
          </el-form-item>

          <el-form-item label="备注" prop="remark">
            <el-input 
              v-model="form.remark" 
              type="textarea" 
              placeholder="可选填写提现备注信息" 
              :rows="3"
            />
          </el-form-item>
        </el-form>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button v-if="hasAccount" type="primary" @click="handleSubmit" :loading="submitLoading" :disabled="accountInfo.auditStatus !== '1'">确认提现</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, toRefs, computed, watch, onMounted } from 'vue'
import { getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
import useAppStore from '@/store/modules/app'
import useUserStore from '@/store/modules/user'
import { submitWithdraw } from '@/api/payment/withdraw'
import { getAccountInfo } from '@/api/payment/account'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  amount: {
    type: Number,
    default: 0
  }
})

const emit = defineEmits(['update:visible', 'submit', 'cancel'])

const { proxy } = getCurrentInstance()
const router = useRouter()
const mobile = computed(() => useAppStore().device === 'mobile')
const loading = ref(false)
const submitLoading = ref(false)
const formRef = ref(null)
const accountInfo = ref({})
const hasAccount = ref(false)

const data = reactive({
  form: {
    amount: 0,
    remark: ''
  }
})

const { form } = toRefs(data)

// 表单校验规则
const rules = {
  remark: [
    { max: 200, message: '备注不能超过200个字符', trigger: 'blur' }
  ]
}

// 监听传入的金额变化
watch(() => props.amount, (val) => {
  form.value.amount = val
}, { immediate: true })

// 监听对话框可见性变化
watch(() => props.visible, (val) => {
  if (val) {
    fetchAccountInfo()
  }
}, { immediate: true })

// 获取账户信息
function fetchAccountInfo() {
  loading.value = true
  getAccountInfo().then(res => {
    console.log(res)
    if (res.code === 200 && res.data) {
      accountInfo.value = res.data
      hasAccount.value = true
    } else {
      hasAccount.value = false
    }
  }).catch(err => {
    console.error('获取账户信息失败', err)
    hasAccount.value = false
  }).finally(() => {
    loading.value = false
  })
}

// 跳转到账户设置页面
function goToAccountSetting() {
  emit('update:visible', false)
  router.push('/setting')
}

// 取消按钮
function handleCancel() {
  emit('update:visible', false)
  emit('cancel')
}

// 提交表单
function handleSubmit() {
  formRef.value.validate((valid) => {
    if (valid) {
      submitLoading.value = true
      
      // 获取当前用户的公寓ID
      const userStore = useUserStore()
      const apartmentId = userStore.apartment.apartmentId
      
      if (!apartmentId) {
        proxy.$modal.msgError('未获取到公寓信息')
        submitLoading.value = false
        return
      }
      
      // 构建提交数据
      const submitData = {
        amount: form.value.amount,
        remark: form.value.remark,
        apartmentId
      }
      
      // 调用提现API
      submitWithdraw(submitData).then(res => {
        if (res.code === 200) {
          proxy.$modal.msgSuccess('提现申请已提交，请等待处理')
          emit('submit', form.value)
          emit('update:visible', false)
          
          // 重置表单
          form.value = {
            amount: props.amount,
            remark: ''
          }
        } else {
          proxy.$modal.msgError(res.msg || '提交失败')
        }
      }).catch(err => {
        console.error('提现申请提交失败', err)
        proxy.$modal.msgError('提交失败，请稍后重试')
      }).finally(() => {
        submitLoading.value = false
      })
    }
  })
}

// 初始化时获取账户信息
onMounted(() => {
  if (props.visible) {
    fetchAccountInfo()
  }
})
</script>

<style scoped>
.p20 {
  padding: 20px;
}
.mt20 {
  margin-top: 20px;
}
.text-center {
  text-align: center;
}
.account-info {
  background-color: #f5f7fa;
  padding: 12px 15px;
  border-radius: 4px;
}
.account-info p {
  margin: 8px 0;
}
.account-info .label {
  color: #606266;
  margin-right: 8px;
  font-weight: 500;
}
</style> 